#!/usr/bin/env bash

# REQUIRES: preload
# RUN: bash %s %T/file_path_relative
# RUN: cd %T/file_path_relative; %{intercept-build} --cdb preload.json ./run.sh
# RUN: cd %T/file_path_relative; %{python} is_file.py preload.json
# RUN: cd %T/file_path_relative; %{python} is_rel.py preload.json

set -o errexit
set -o nounset
set -o xtrace

# the test creates a subdirectory inside output dir.
#
# ${root_dir}
# ├── run.sh
# ├── is_file.py
# ├── is_rel.py
# └── src
#    └── empty.c

root_dir=$1
mkdir -p "${root_dir}/src"

touch "${root_dir}/src/empty.c"

build_file="${root_dir}/run.sh"
cat > ${build_file} << EOF
#!/usr/bin/env bash

set -o nounset
set -o xtrace

\$CC -c -Dver=1 src/empty.c;
\$CXX -c -Dver=2 src/empty.c;

cd src

\$CC -c -Dver=1 empty.c;
\$CXX -c -Dver=2 empty.c;
EOF
chmod +x ${build_file}

cat > "${root_dir}/is_file.py" << EOF
#!/usr/bin/env python

import argparse
import json
import sys
import os.path


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('input', type=argparse.FileType('r'))
    args = parser.parse_args()
    # file is open, parse the json content
    input = json.load(args.input)
    # just get directory paths
    return [os.path.isfile(os.path.join(entry['directory'], entry['file'])) \
            for entry in input].count(False)


if __name__ == '__main__':
    sys.exit(main())
EOF

cat > "${root_dir}/is_rel.py" << EOF
#!/usr/bin/env python

import argparse
import json
import sys
import os.path


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('input', type=argparse.FileType('r'))
    args = parser.parse_args()
    # file is open, parse the json content
    input = json.load(args.input)
    # just get directory paths
    return [os.path.isabs(entry['file']) for entry in input].count(True)


if __name__ == '__main__':
    sys.exit(main())
EOF
